import { useState, useEffect, useRef } from "react";

function useIndex(props: any) {
  const { tabIndex = "0" } = props;
  // 是否展示回到底部

  const [showBack, setShowBack] = useState(false);
  const scrollDomRef = useRef<any>(null);
  const scrollRef = useRef(0);

  const scrollToBottom = () => {
    try {
      if (tabIndex === "0") {
        if (scrollDomRef.current) {
          setTimeout(() => {
            try {
              scrollDomRef.current.scrollTop =
                scrollDomRef.current?.scrollHeight -
                scrollDomRef.current?.clientHeight;
            } catch (e) {

            }
          }, 400);
        }
      }
    } catch (e) {

    }
  };

  useEffect(() => {
    if (tabIndex !== "0") {
      return;
    }
    if (scrollDomRef.current) {
      scrollDomRef.current.addEventListener("scroll", () => {
        // 判断是否滚动上去
        const isAtBottom =
          scrollDomRef.current.scrollHeight -
          scrollDomRef.current.scrollTop -
          20 >
          scrollDomRef.current.clientHeight;
        setShowBack(isAtBottom);
      });
    }
    return scrollDomRef.current.removeEventListener("scroll", () => { });
  }, [scrollDomRef, tabIndex]);

  useEffect(() => {
    if (tabIndex === "0") {
      scrollToBottom();
    }
  }, [tabIndex]);

  return {
    showBack,
    scrollRef,
    scrollDomRef,
    scrollToBottom,
  };
}

export default useIndex;
